package com.raos.xdocreport.utils;

import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * word 生成工具类
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2022/2/27 17:49
 */
public class WordUtil {

    private static final Logger logger = LoggerFactory.getLogger(WordUtil.class);

    private WordUtil() { }

    /**
     * 按照模板生成Word
     *
     * @param response 响应对象
     * @param template 模板文件
     * @param data 数据map
     * @param outFileName 输出文件名
     */
    public static void generateWord(HttpServletResponse response, File template, Map<String, Object> data, String outFileName) {
        if(response == null || template == null || data == null || outFileName == null) {
            logger.error("传递参数不完整，无法处理");
            throw new RuntimeException("传递参数不完整，无法处理");
        }
        try {
            InputStream ins = new FileInputStream(template);
            // 注册xdocreport实例并加载FreeMarker模板引擎
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);

            //创建xdocreport上下文对象
            IContext context = report.createContext();

            // 设置数据
            context.putMap(data);

            // 设置浏览器端下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(outFileName, "UTF-8"))));
            report.process(context, response.getOutputStream());
        } catch (Exception e) {
            logger.error("按照模板生成Word时发生异常！", e);
            e.printStackTrace();
        }
    }

}
